package com.djnt.catering.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.djnt.catering.Marshal;

/**
 * This class helps open, create, and upgrade the database file.
 */
class DatabaseHelper extends SQLiteOpenHelper {
	private static final String DATABASE_NAME = "catering.db";
	private static final int DATABASE_VERSION = 11;
	private static final String TAG = "DatabaseHelper";
	private Marshal mMarshal;

	DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		mMarshal = new Marshal(context);
	}

	@Override
	public void onOpen(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		super.onOpen(db);
		/*
		 * mMarshal.addCustomFunction(db, "MATCHER", 2, new
		 * Marshal.CustomFunction() {
		 * 
		 * @Override public void callback(String[] args) { // TODO
		 * Auto-generated method stub
		 * 
		 * } });
		 */
	}

	@Override
	public synchronized void close() {
		// TODO Auto-generated method stub
		mMarshal.releaseCustomFunction();
		super.close();
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		Province.onCreate(db);
		City.onCreate(db);
		HotNews.onCreate(db);
		CompanyUsers.onCreate(db);
		createViewsAndTriggers(db);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
				+ newVersion + ", which will destroy all old data");
		boolean upgradeViewsAndTriggers = false;
		if (oldVersion < 6) {
			db.execSQL("DROP TABLE IF EXISTS " + Province.TABLE_NAME);
			db.execSQL("DROP TABLE IF EXISTS " + City.TABLE_NAME);
			db.execSQL("DROP TABLE IF EXISTS " + HotNews.TABLE_NAME);
			onCreate(db);
			return;
		}
		if (oldVersion == 6) {
			CompanyUsers.onCreate(db);
			oldVersion++;
		}
		if (oldVersion == 7) {
			upgradeViewsAndTriggers = true;
			oldVersion++;
		}
		if (oldVersion == 8) {
			upgradeViewsAndTriggers = true;
			db.execSQL("ALTER TABLE " + CompanyUsers.TABLE_NAME
					+ " ADD COLUMN " + CompanyUsers.LOGO + " TEXT");
			oldVersion++;
		}
		if (oldVersion == 9) {
			upgradeViewsAndTriggers = true;
			oldVersion++;
		}
		if (oldVersion == 10) {
			upgradeViewsAndTriggers = true;
			oldVersion++;
		}

		if (upgradeViewsAndTriggers) {
			createViewsAndTriggers(db);
		}
		if (oldVersion != newVersion) {
			throw new IllegalStateException(
					"error upgrading the database to version " + newVersion);
		}
	}

	private void createViewsAndTriggers(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		ViewCityProvince.onCreate(db);
		ViewHotNewsUsers.onCreate(db);
	}
}
